<template>
  <view class="wallet-bg">
    <view class="wallet-head-card">
      <view class="card-title">我的钱包</view>
      <view class="card-balance">{{ balance ? parseFloat(balance).toFixed(2) : '0.00' }}</view>
      <image class="card-bgicon" src="/static/wallet-bg.png" mode="aspectFit" />
    </view>
    <view class="tabbar">
      <view :class="['tab', tab==='profit'?'active':'']" @click="tab='profit'">收益记录</view>
      <view :class="['tab', tab==='cost'?'active':'']" @click="tab='cost'">消费记录</view>
      <view :class="['tab', tab==='recharge'?'active':'']" @click="tab='recharge'">充值记录</view>
      <view :class="['tab', tab==='withdraw'?'active':'']" @click="tab='withdraw'">提现记录</view>
    </view>
    <scroll-view 
      class="record-card" 
      scroll-y 
      @scrolltolower="onScrollToLower"
      :enable-back-to-top="true"
    >
      <!-- 收益记录 -->
      <view v-if="tab === 'profit'">
        <view v-if="profitList.length > 0">
          <view 
            v-for="(item, index) in profitList" 
            :key="item.id || index" 
            class="profit-item"
          >
            <view class="left">
              <view class="title">{{ item.bizTypeName || item.typeName || '收益' }}</view>
              <view class="time">{{ formatDate(item.createTime) }}</view>
            </view>
            <view class="val profit">+{{ formatBalance(item.amount) }}</view>
          </view>
        </view>
        <view v-else-if="!loadingProfit" class="empty">暂无记录</view>
        <view v-else class="empty">加载中...</view>
        <view v-if="profitList.length > 0 && profitHasMore" class="load-more">上拉加载更多</view>
        <view v-if="profitList.length > 0 && !profitHasMore && profitList.length >= profitPageSize" class="load-more no-more">没有更多了</view>
      </view>
      
      <!-- 消费记录 -->
      <view v-else-if="tab === 'cost'">
        <view v-if="costList.length > 0">
          <view 
            v-for="(item, index) in costList" 
            :key="item.id || index" 
            class="profit-item"
          >
            <view class="left">
              <view class="title">{{ item.bizTypeName || item.typeName || '消费' }}</view>
              <view class="time">{{ formatDate(item.createTime) }}</view>
            </view>
            <view class="val cost">-{{ formatBalance(item.amount) }}</view>
          </view>
        </view>
        <view v-else-if="!loadingCost" class="empty">暂无记录</view>
        <view v-else class="empty">加载中...</view>
        <view v-if="costList.length > 0 && costHasMore" class="load-more">上拉加载更多</view>
        <view v-if="costList.length > 0 && !costHasMore && costList.length >= costPageSize" class="load-more no-more">没有更多了</view>
      </view>
      
      <!-- 充值记录 -->
      <view v-else-if="tab === 'recharge'">
        <view v-if="rechargeList.length > 0">
          <view 
            v-for="(item, index) in rechargeList" 
            :key="item.id || index" 
            class="profit-item"
          >
            <view class="left">
              <view class="title">{{ item.bizTypeName || item.typeName || '充值' }}</view>
              <view class="time">{{ formatDate(item.createTime) }}</view>
            </view>
            <view class="val profit">+{{ formatBalance(item.amount) }}</view>
          </view>
        </view>
        <view v-else-if="!loadingRecharge" class="empty">暂无记录</view>
        <view v-else class="empty">加载中...</view>
        <view v-if="rechargeList.length > 0 && rechargeHasMore" class="load-more">上拉加载更多</view>
        <view v-if="rechargeList.length > 0 && !rechargeHasMore && rechargeList.length >= rechargePageSize" class="load-more no-more">没有更多了</view>
      </view>
      
      <!-- 提现记录 -->
      <view v-else-if="tab === 'withdraw'">
        <view v-if="withdrawList.length > 0">
          <view 
            v-for="(item, index) in withdrawList" 
            :key="item.id || index" 
            class="profit-item"
          >
            <view class="left">
              <view class="title">提现申请</view>
              <view class="time">{{ formatDate(item.createTime) }}</view>
            </view>
            <view class="val cost">-{{ formatBalance(item.amount) }}</view>
          </view>
        </view>
        <view v-else-if="!loadingWithdraw" class="empty">暂无记录</view>
        <view v-else class="empty">加载中...</view>
      </view>
    </scroll-view>
    <view class="wallet-bottom-btns">
      <button class="btn plain" @click="to('recharge')">去充值</button>
      <button class="btn gradient" @click="to('withdraw')">去提现</button>
    </view>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app'

const tab = ref('profit')
const balance = ref(0)

// 收益记录相关
const profitList = ref([])
const loadingProfit = ref(false)
const profitPage = ref(1)
const profitPageSize = ref(10)
const profitTotal = ref(0)
const profitHasMore = ref(true)

// 消费记录相关
const costList = ref([])
const loadingCost = ref(false)
const costPage = ref(1)
const costPageSize = ref(10)
const costTotal = ref(0)
const costHasMore = ref(true)

// 充值记录相关
const rechargeList = ref([])
const loadingRecharge = ref(false)
const rechargePage = ref(1)
const rechargePageSize = ref(10)
const rechargeTotal = ref(0)
const rechargeHasMore = ref(true)

// 提现记录相关
const withdrawList = ref([])
const loadingWithdraw = ref(false)
const withdrawPage = ref(1)
const withdrawPageSize = ref(10)
const withdrawTotal = ref(0)

// 格式化余额显示（将分转换为元，保留两位小数）
const formatBalance = (value) => {
  // 如果值是分（整数），转换为元
  if (value && value >= 100) {
    return (value / 100).toFixed(2)
  }
  // 如果已经是元（小数），直接格式化
  if (value) {
    return parseFloat(value).toFixed(2)
  }
  return '0.00'
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取钱包交易记录列表（收益、消费、充值）
const getTransactionList = async (type) => {
  let list, loading, page, pageSize, total, hasMore
  
  if (type === 3) {
    // 收益记录
    list = profitList
    loading = loadingProfit
    page = profitPage
    pageSize = profitPageSize
    total = profitTotal
    hasMore = profitHasMore
  } else if (type === 2) {
    // 消费记录
    list = costList
    loading = loadingCost
    page = costPage
    pageSize = costPageSize
    total = costTotal
    hasMore = costHasMore
  } else if (type === 1) {
    // 充值记录
    list = rechargeList
    loading = loadingRecharge
    page = rechargePage
    pageSize = rechargePageSize
    total = rechargeTotal
    hasMore = rechargeHasMore
  }
  
  if (loading.value) return
  
  loading.value = true
  try {
    const WalletApi = (await import('@/sheep/api/member/wallet')).default
    const res = await WalletApi.getWalletTransactionPage({
      pageNo: page.value,
      pageSize: pageSize.value,
      type: type
    })
    
    if (res && res.code === 0 && res.data) {
      const listData = res.data.list || []
      const totalData = res.data.total || 0
      
      if (page.value === 1) {
        list.value = listData
      } else {
        list.value = [...list.value, ...listData]
      }
      total.value = totalData
      hasMore.value = list.value.length < totalData
    }
  } catch (error) {
    console.error(`获取${type === 1 ? '充值' : type === 2 ? '消费' : '收益'}记录失败:`, error)
    uni.showToast({
      title: '加载失败，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 获取提现记录列表
const getWithdrawList = async () => {
  if (loadingWithdraw.value) return
  
  loadingWithdraw.value = true
  try {
    const UserApi = (await import('@/sheep/api/member/user')).default
    const res = await UserApi.getWithdrawPage({
      pageNo: withdrawPage.value,
      pageSize: withdrawPageSize.value
    })
    
    if (res && res.code === 0 && res.data) {
      const listData = res.data.list || []
      const totalData = res.data.total || 0
      
      if (withdrawPage.value === 1) {
        withdrawList.value = listData
      } else {
        withdrawList.value = [...withdrawList.value, ...listData]
      }
      withdrawTotal.value = totalData
    }
  } catch (error) {
    console.error('获取提现记录失败:', error)
  } finally {
    loadingWithdraw.value = false
  }
}

// 监听标签切换
watch(tab, (newTab) => {
  if (newTab === 'profit') {
    // 切换到收益记录
    if (profitList.value.length === 0) {
      profitPage.value = 1
      profitList.value = []
      getTransactionList(3)
    }
  } else if (newTab === 'cost') {
    // 切换到消费记录
    if (costList.value.length === 0) {
      costPage.value = 1
      costList.value = []
      getTransactionList(2)
    }
  } else if (newTab === 'recharge') {
    // 切换到充值记录
    if (rechargeList.value.length === 0) {
      rechargePage.value = 1
      rechargeList.value = []
      getTransactionList(1)
    }
  } else if (newTab === 'withdraw') {
    // 切换到提现记录
    if (withdrawList.value.length === 0) {
      withdrawPage.value = 1
      withdrawList.value = []
      getWithdrawList()
    }
  }
})

// 滚动到底部加载更多
const onScrollToLower = () => {
  if (tab.value === 'profit' && profitHasMore.value && !loadingProfit.value) {
    profitPage.value++
    getTransactionList(3)
  } else if (tab.value === 'cost' && costHasMore.value && !loadingCost.value) {
    costPage.value++
    getTransactionList(2)
  } else if (tab.value === 'recharge' && rechargeHasMore.value && !loadingRecharge.value) {
    rechargePage.value++
    getTransactionList(1)
  }
}

// 获取用户信息（获取余额）
const getUserInfo = async () => {
  try {
    const UserApi = (await import('@/sheep/api/member/user')).default
    const res = await UserApi.getUserInfo()
    if (res && res.code === 0 && res.data) {
      balance.value = res.data.balance || 0
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

function to(type) {
  if (type === 'withdraw') {
    uni.navigateTo({ url: '/pages/user/withdraw' })
  } else if (type === 'recharge') {
    uni.navigateTo({ url: '/pages/user/recharge' })
  } else {
    uni.showToast({ title: '未知操作', icon: 'none' })
  }
}

// 页面加载时获取用户信息和默认列表
onLoad(() => {
  getUserInfo()
  // 默认加载收益记录
  getTransactionList(3)
})
</script>

<style lang="scss" scoped>
.wallet-bg { 
  min-height: 100vh; 
  background: #f7f7fa; 
  display: flex;
  flex-direction: column;
  padding-bottom: 20rpx;
}
.wallet-head-card {
  margin: 30rpx 18rpx 0 18rpx;
  background-image: url('/static/money-bj.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 24rpx;
  padding: 40rpx 44rpx 32rpx 44rpx;
  position: relative;
  overflow: hidden;
  color: #fff;
  .card-title {
    font-size: 27rpx;
    margin-bottom: 24rpx;
    font-weight: 400;
  }
  .card-balance {
    font-size: 56rpx;
    font-weight: bold;
    margin-bottom: 0;
  }
  .card-bgicon {
    position: absolute;
    right: 22rpx;
    top: 18rpx;
    width: 160rpx;
    height: 110rpx;
    opacity: 0.18;
  }
}
.tabbar {
  display: flex;
  align-items: center;
  padding: 6rpx 0 2rpx 0;
  margin: 20rpx 0 2rpx 0;
  border-bottom: none;
  .tab {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    font-weight: 500;
    color: #999;
    padding: 22rpx 0 14rpx 0;
    position: relative;
    background: transparent;
    transition: color 0.12s;
    &.active {
      color: #18181d;
      font-weight: 700;
      &::after{
        content: '';
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
        bottom: 4rpx;
        width: 60rpx;
        height: 7rpx;
        border-radius: 10rpx;
        background: #18181d;
      }
    }
  }
}
.record-card {
  margin: 22rpx 18rpx 0 18rpx;
  background: #fff;
  border-radius: 22rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.04);
  min-height: 240rpx;
  height: calc(100vh - 600rpx);
  padding: 12rpx 0 12rpx 0;
  flex: 1;
  box-sizing: border-box;
  .profit-item {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    padding: 26rpx 38rpx 16rpx 38rpx;
    border-bottom: 1px solid #f1f2f5;
    &:last-child{border-bottom:none;}
    .left{
      display:flex; flex-direction:column;
      .title{font-size:28rpx;font-weight:500;color:#222;margin-bottom:13rpx;}
      .time{font-size:20rpx;color:#afb4be;}
    }
    .val{
      font-size:32rpx;
      font-weight:bold;
      align-self:center;
      &.profit{color:#2468ff;}
      &.cost{color:#ff6b6b;}
    }
  }
  .empty{
    height:160rpx;
    text-align:center;
    color:#bbb;
    font-size:29rpx;
    display:flex;
    justify-content:center;
    align-items:center;
  }
  .load-more {
    text-align: center;
    padding: 20rpx 0;
    color: #999;
    font-size: 24rpx;
    &.no-more {
      color: #ccc;
    }
  }
}
.wallet-bottom-btns {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 12rpx;
  margin: 30rpx 0 120rpx 0;
  padding: 0 42rpx;
  .btn {
    height: 80rpx;
    border-radius: 900rpx;
    font-size: 30rpx;
    min-width: 200rpx;
    font-weight: 400;
    letter-spacing: 2rpx;
    border: none;
    &.plain {
      background: #fff;
      color: #212121;
      border: 1px solid #ededed;
    }
    &.gradient {
      background: linear-gradient(90deg,#b488ff 0%,#7fc2ff 100%);
      color: #fff;
      box-shadow: 0 2rpx 12rpx #bbbeee40;
    }
  }
}
</style>
